/*
* @Author: dyiwen
* @Date:   2020-09-17 19:00:02
* @Last Modified by:   dyiwen
* @Last Modified time: 2020-09-21 17:12:26
 */
package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/dyiwen/nacos-golang"
	"github.com/modood/table"
	"github.com/widuu/goini"
	"io/ioutil"
	"os"
)

func login(url, prefix, namespace, user, password, logdir, cachedir string, port uint64) error {
	a := nacos.InitConfig(url, prefix, namespace, user, password, logdir, cachedir, port)
	_, err := a.CreateConfigClient()
	return err
}

//漂亮打印
func pprintf(content []Table) {
	t := table.Table(content)
	fmt.Println(t)
}

// 生成配置文件
func write_to_config(c Config) (err error) {
	b, err := json.Marshal(c)
	if err != nil {
		return err
	}
	err = CreatePath(b, path)
	// err = ioutil.WriteFile(path, b, os.ModeAppend)
	if err != nil {
		return err
	}
	return
}

// 读取文件内容
func file_get_contents(path string) ([]byte, error) {
	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		fmt.Println("请先执行nacosctl login!")
		return nil, err
	}
	return ioutil.ReadAll(f)
}

//json to struct
func json_to_struct(context string) (err error) {
	err = json.Unmarshal([]byte(context), &nsbox)
	return
}

// json文件转struct
func file_to_struct() (err error) {
	content, err := file_get_contents(path)
	if err != nil {
		return err
	}
	err = json.Unmarshal([]byte(content), &conf)
	if err != nil {
		return err
	}
	return err
}

// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
	_, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

func RemoveFile(path string) (err error) {
	if Exists(path) {
		err = os.Remove(path)
	}
	return err
}

// 判断所给路径是否为文件夹
func IsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// 解析ini配置文件
func ParseIniConfig(path string) (string, []map[string]map[string]string) {
	conf := goini.SetConfig(path)
	box := conf.ReadList()
	mjson, _ := json.MarshalIndent(box, " ", " ")
	return string(mjson), box
}

func MapMergeToString(input map[string]string) string {
	var output string = ""
	for k, v := range input {
		output = output + fmt.Sprintf("%s=%s\n", k, v)
	}
	return output
}

/*
判断路径是否为文件
*/
func IsFile(path string) bool {
	fi, e := os.Stat(path)
	if e != nil {
		return false
	}
	return !fi.IsDir()
}

/*
不存在则创建文件
*/
func CreatePath(content []byte, path string) (err error) {
	// ok := Exists(path)
	// if !ok {
	// err = os.Create(path)
	// }
	// return
	f, err := os.Create(path)
	defer f.Close()
	if err != nil {
		return err
	}
	_, err = f.Write(content)
	return
}

/*
获取环境变量
*/
func GetEnv(param string) string {
	return os.Getenv(param)
}
